﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using LIMS.Entities;
using LIMS.Shared;
namespace LIMS.Windows
{
    public partial class SiteManagement :LIMSPageBase<SiteManagementPresenter>, ISiteManagementPageView
    {
        public SiteManagement()
        {
            InitializeComponent();
        }


        /// <summary>
        /// btnSearch_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            string sCriteria = txtSearch.Text.Trim();
            if (sCriteria.Length > 0)
            {
                if (sCriteria.Contains("*"))
                {
                    if (sCriteria.Equals("*"))
                    {
                        sCriteria = string.Empty;
                    }
                    else
                    {
                        sCriteria = sCriteria.Replace("*", "%");
                    }
                }
                else if (sCriteria.Contains("?"))
                {
                    sCriteria = sCriteria.Replace("?", "%");
                }
            }
            GetSitesBasedOnCriteria(sCriteria);
            ClearData();
        }

        /// <summary>
        /// btnAddNewUser_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddNewSite_Click(object sender, EventArgs e)
        {
            EnableDisableControls(true);
            btnEdit.Enabled = false;
            btnDelete.Enabled = false;
            txtSiteName.Focus();
            Site newSite = new Site();
            oSite.Add(newSite);
            CurrentIndex = oSite.Count - 1;
            cmbStatus.SelectedIndex = 0;
        }

        /// <summary>
        /// Enable disable form controls on action basis.
        /// if bValue is true contrlos will be enabled else disabled.
        /// </summary>
        /// <param name="bValue"></param>
        private void EnableDisableControls(bool bValue)
        {
            try
            {
                txtLocation.Enabled = bValue;
                txtSiteName.Enabled = bValue;
                cmbStatus.Enabled = bValue;
                btnSaveSite.Enabled = bValue;
                btnClear.Enabled = bValue;
              
            }
            catch (Exception ex)
            { }
        }

        /// <summary>
        /// grdSite_CellClick
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grdSite_CellClick(object sender, DataGridViewCellEventArgs e)
        {

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void grdSite_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            bool bChkBoxSelected = false;
            int iSiteID = Convert.ToInt32(grdSite.Rows[grdSite.CurrentRow.Index].Cells["Id"].Value);
            m_iSiteId = iSiteID;

            for (int iRowCount = 0; iRowCount < grdSite.Rows.Count; iRowCount++)
            {
                DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdSite.Rows[iRowCount].Cells[0];
                if (cell is DataGridViewCheckBoxCell)
                {
                    if ((bool)cell.EditedFormattedValue)
                    {
                        bChkBoxSelected = true;
                        break;
                    }
                }
            }
            if (bChkBoxSelected)
            {
                btnDelete.Enabled = true;
                btnEdit.Enabled = true;
            }
            else
            {
                btnDelete.Enabled = false;
                btnEdit.Enabled = false;
            }

        }





        private static int m_iSiteId = 0;
        /// <summary>
        /// btnEdit_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (m_iSiteId > 0)
            {
                int iSelectedRowsCount = 0;
                int iRowIndex = 0;
                for (int iRowCount = 0; iRowCount < grdSite.Rows.Count; iRowCount++)
                {
                    DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdSite.Rows[iRowCount].Cells[0];
                    if (cell is DataGridViewCheckBoxCell)
                    {
                        if ((bool)cell.EditedFormattedValue)
                        {
                            iRowIndex = iRowCount;
                            iSelectedRowsCount++;
                        }
                    }
                }
                if (iSelectedRowsCount > 1)
                {
                    MessageBox.Show("Select single row to edit the record.");
                    return;
                }
                else if (iSelectedRowsCount == 0)
                {
                    MessageBox.Show("Select atleast one record to edit.");
                    return;
                }

                /// Edit
                CurrentIndex = iRowIndex;
                EnableDisableControls(true);
                btnClear.Enabled = false;
             

            }
        }
        /// <summary>
        /// btnDelete_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (m_iSiteId > 0)
            {
                int iSelectedRowsCount = 0;
                for (int iRowCount = 0; iRowCount < grdSite.Rows.Count; iRowCount++)
                {
                    DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdSite.Rows[iRowCount].Cells[0];
                    if (cell is DataGridViewCheckBoxCell)
                    {
                        if ((bool)cell.EditedFormattedValue)
                        {
                            iSelectedRowsCount++;
                        }
                    }
                }
                if (iSelectedRowsCount == 0)
                {
                    MessageBox.Show("Select atleast one record to delete.");
                    return;
                }

                DialogResult oResult = MessageBox.Show("Are you sure to delete the selected records?", "Delete site", MessageBoxButtons.YesNo);
                if (oResult.Equals(DialogResult.Yes))
                {
                    /// Delete
                    for (int iRowCount = 0; iRowCount < grdSite.Rows.Count; iRowCount++)
                    {


                        DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)grdSite.Rows[iRowCount].Cells[0];
                        if (cell is DataGridViewCheckBoxCell)
                        {
                            if ((bool)cell.EditedFormattedValue)
                            {
                                if (CheckPlantDetailForSite(oSite[iRowCount].Id))
                                {
                                    this.Presenter.Delete(oSite[iRowCount]);
                                }

                                else
                                {
                                    MessageBox.Show( "This Site " +oSite[iRowCount].Name+  Resource.CANNOT_DELETE);                              
                                }
                            }
                        }
                    }
                    this.Presenter.InitializeView();
                    DisplayGrid();
                    ClearData();
                }

            }
        }
        /// <summary>
        /// CheckPlantDetailForSite
        /// </summary>
        /// <param name="SiteID"></param>
        /// <returns></returns>
        private bool CheckPlantDetailForSite(int SiteID)
        {
           bool bIsDeleted = false;
           bIsDeleted = this.Presenter.GetPlantBySiteId(SiteID);
           return bIsDeleted;
        }






        /// <summary>
        /// DisplayGrid
        /// </summary>
        private void DisplayGrid()
        {

            if (grdSite.Columns[0].Displayed == false)
            {
                DataGridViewCheckBoxColumn oChkColumn = new DataGridViewCheckBoxColumn(false);

                oChkColumn.HeaderText = "Select";
                oChkColumn.Name = "Select";
                oChkColumn.Width = 50;

                grdSite.Columns.Insert(0, oChkColumn);
            }

            grdSite.MultiSelect = false;
            grdSite.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            grdSite.AllowUserToAddRows = false;

            foreach (DataGridViewColumn dc in grdSite.Columns)
            {
                if (dc.Index.Equals(0))
                {
                    dc.ReadOnly = false;
                }
                else
                {
                    dc.ReadOnly = true;
                }
            }
            grdSite.RowHeadersVisible = false;
        }
        /// <summary>
        /// btnSaveSite_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveSite_Click(object sender, EventArgs e)
        {
            try
            {

                if (Validations.IsEmpty(txtLocation.Text.Trim()) ||  Validations.IsEmpty(txtSiteName.Text.Trim()) ||
                    Validations.IsCmbboxDefaultValue(Convert.ToString(cmbStatus.SelectedValue)))
                {
                    MessageBox.Show("Fill mandatory(*) information.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {

                    oSite[CurrentIndex].Name = txtSiteName.Text; ;
                    oSite[CurrentIndex].Location = txtLocation.Text;
                    oSite[CurrentIndex].Status = Convert.ToString(cmbStatus.SelectedValue);
                    oSite[CurrentIndex].CreatedBy = 1; /// logged in user
                    oSite[CurrentIndex].CreatedDateTime = DateTime.Now;


                    ///save site.
                    if (this.Presenter.Save(oSite[CurrentIndex]))
                    {
                        MessageBox.Show("Site saved successfully.");

                        EnableDisableControls(false);
                        btnEdit.Enabled = false;
                        btnDelete.Enabled = false;
                        ClearData();
                    }
                    ///intialize grid after saving site..

                    this.Presenter.InitializeView();
                    DisplayGrid();

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error while saving site .");
            }
        }
        /// <summary>
        /// ClearData
        /// </summary>
        private void ClearData()
        {
            try
            {
                txtSiteName.Text = string.Empty;
                txtLocation.Text = string.Empty;
                cmbStatus.SelectedValue = "X";
            }
            catch (Exception ex)
            {
                Logger.Error("Error while clear control of site managment");
            }
        }

        /// <summary>
        /// GetSitesBasedOnCriteria
        /// </summary>
        /// <param name="p_sCriteria"></param>
        private void GetSitesBasedOnCriteria(string p_sCriteria)
        {
            try
            {
                if (txtSearch.Text.Trim().Length == 0)
                {
                    this.Presenter.InitializeView();
                    DisplayGrid();
                }
                else
                {
                    this.Presenter.SearchSiteByKeyword(p_sCriteria);
                    DisplayGrid();
                }
                //DisplayGrid();
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

        /// <summary>
        /// btnPrevious_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrevious_Click(object sender, EventArgs e)
        {
            try
            {
                if (GridData.PageIndex > 1)
                {
                    GridData.PageIndex--;
                    GetSitesBasedOnCriteria(string.Empty);
                   
                }
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }

        }

        /// <summary>
        /// btnLast_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLast_Click(object sender, EventArgs e)
        {
            try
            {
                GridData.PageIndex = (GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0));
                GetSitesBasedOnCriteria(string.Empty);
              
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }
        /// <summary>
        /// btnSpecific_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSpecific_Click(object sender, EventArgs e)
        {
            try
            {
                int userCurrentPage = 0;

                if (!int.TryParse(txtPageNo.Text, out userCurrentPage))
                {
                    userCurrentPage = 1;
                }

                int maxPageSize = (GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0));
                if (userCurrentPage > maxPageSize)
                {
                    userCurrentPage = 1;
                }
                GridData.PageIndex = userCurrentPage;
                GetSitesBasedOnCriteria(string.Empty);
              
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }
        /// <summary>
        /// btnNext_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNext_Click(object sender, EventArgs e)
        {
            try
            {
                int maxPageSize = (GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0) - 1);

                if (GridData.PageIndex <= maxPageSize)
                {
                    GridData.PageIndex++;
                    GetSitesBasedOnCriteria(string.Empty);
                  
                }
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }



        #region ISiteManagementPageView Members

        private int iCurrentIndex;
        public int CurrentIndex
        {
            set
            {
                iCurrentIndex = value;
                txtSiteName.Text = oSite[iCurrentIndex].Name;
                txtLocation.Text = oSite[iCurrentIndex].Location;
                cmbStatus.SelectedValue =   oSite[CurrentIndex].Status;
                //  cmbStatus.SelectedValue   = Resource.GetCodedStatus(oSite[iCurrentIndex].Status, true);

            }
            get
            {
                return iCurrentIndex;
            }
        }

        public void FillPageData()
        {
            //throw new NotImplementedException();
        }
        /// <summary>
        /// GridViewData
        /// </summary>
        private GridViewData oGridData;
        public GridViewData GridData
        {
            set
            {
                oGridData = value;
                lblTotal.Text = "/ " + (value.TotalRecords / value.PageSize + ((value.TotalRecords % value.PageSize > 0) ? 1 : 0)).ToString();
                txtPageNo.Text = value.PageIndex.ToString();
            }
            get
            {
                if (oGridData != null)
                {
                    return oGridData;
                }
                else
                {
                    GridViewData grdData = new GridViewData();
                    grdData.SortOrder = "ASC";
                    grdData.SortColumn = "CreatedDateTime";
                    grdData.PageSize = 5;//SetGridPageSize();
                    grdData.PageIndex = 1;
                    return grdData;
                }

            }
        }
        /// <summary>
        /// ShowMessage
        /// </summary>
        /// <param name="type"></param>
        /// <param name="sMessage"></param>
        public void ShowMessage(MessageType type, string sMessage)
        {
            //throw new NotImplementedException();
        }

        private List<Site> oSite;
        public List<Site> Sites
        {
            get
            {
                if (oSite == null)
                {
                    oSite = new List<Site>();
                }
                return oSite;
            }
            set
            {
                oSite = value;
                grdSite.DataSource = ConvertListToDataTable(oSite);
                grdSite.Columns[0].Visible = false;
            }
        }
        /// <summary>
        /// ConvertListToDataTable
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private DataTable ConvertListToDataTable(List<Site> list)
        {
            // New table.
            DataTable table = new DataTable();
            DataColumn oColumn0 = new DataColumn("Id", typeof(int));
            DataColumn oColumn1 = new DataColumn("NAME", typeof(string));
            DataColumn oColumn2 = new DataColumn("LOCATION", typeof(string));
            DataColumn oColumn3 = new DataColumn("STATUS", typeof(string));

            table.Columns.Add(oColumn0);
            table.Columns.Add(oColumn1);
            table.Columns.Add(oColumn2);
            table.Columns.Add(oColumn3);


            for (int i = 0; i < list.Count; i++)
            {
                DataRow oNewRow = table.NewRow();
                oNewRow["Id"] = list[i].Id;
                oNewRow["NAME"] = list[i].Name;
                oNewRow["LOCATION"] = list[i].Location;

                oNewRow["STATUS"] = SharedResource.GetCodedStatus(list[i].Status);
                table.Rows.Add(oNewRow);
            }
            return table;
        }


        /// <summary>
        /// GetCodedStatus
        /// </summary>
        /// <param name="StatusValue"></param>
        /// <returns></returns>
        private string GetCodedStatus(string StatusValue)
        {

            string status = string.Empty;

            try
            {
                if (StatusValue.ToUpper().Trim().Equals("A"))
                {
                    status = "Active";
                }
                else if (StatusValue.ToUpper().Trim().Equals("D"))
                {
                    status = "Deactive";
                }
            }
            catch (Exception ex)
            {

            }
            return status;

        }
        #endregion

        /// <summary>
        /// SiteManagement_Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SiteManagement_Load(object sender, EventArgs e)
        {
            bindStatus();
            this.Presenter.InitializeView();
            DisplayGrid();
            GridPagingToolTip();
            EnableDisableControls(false);
            btnDelete.Enabled = false;
            btnEdit.Enabled = false;
            ClearData();
        }

        private void GridPagingToolTip()
        {
            System.Windows.Forms.ToolTip ToolTipText = new System.Windows.Forms.ToolTip();
            ToolTipText.SetToolTip(this.btnNext, "Next");
            ToolTipText.SetToolTip(this.btnFirst, "First");
            ToolTipText.SetToolTip(this.btnPrevious, "Previous");
            ToolTipText.SetToolTip(this.btnLast, "Last");
            ToolTipText.SetToolTip(this.btnSpecific, "Go to specific");
        }

        private void bindStatus()
        {

            cmbStatus.DataSource = Resource.BindStatus();
            cmbStatus.DisplayMember = "StatusValue";
            cmbStatus.ValueMember = "StatusKey";
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearData();

        }

        private void btnFirst_Click(object sender, EventArgs e)
        {
            try
            {
                GridData.PageIndex = 1;//(GridData.TotalRecords / GridData.PageSize + ((GridData.TotalRecords % GridData.PageSize > 0) ? 1 : 0) -1 );
                GetSitesBasedOnCriteria(string.Empty);
            }
            catch (Exception ex)
            {
                //Logger.Error("Error occured.", ex);
            }
        }

    }
}
